#include "ColumnConfig.h"
#include <QDir>
//#include "../ConfigUtility/Include/SettingMgr.h"
//#include "constant2.h"
#include "Main/qstringhandle.h"
#include <QTextCodec>

using namespace ApConst;
const QString LIST_CFG_ID			= "/EnColumnNames";
const QString LIST_CFG_NAME			= "/CnColumnNames";
const QString LIST_CFG_ALIGN			= "/ColumnAligns";
const QString LIST_CFG_USER_ID       = "/ColumnsVisiables";
const QString LIST_CFG_WIDTH         = "/ColumnWidths";
const QString LIST_CFG_INDEX         = "/ColumnIndexs";

CColumnConfig::CColumnConfig()
{
    m_sCfgFullName = QDir::currentPath() + "/GridColumn.ini";
    m_gridInfo = std::make_shared<QSettings>(m_sCfgFullName, QSettings::IniFormat);
    m_gridInfo->setIniCodec(QTextCodec::codecForName("UTF-8"));
}

CColumnConfig::~CColumnConfig()
{

}

QList<QString> CColumnConfig::getRoleNames(QString qsSection)
{
//    QString servers = m_gridInfo->value(qsSection+"/IDs").toString();
//    QStringList lIDs = strutils::explode(SEPARATOR_RECORD[0], servers);

    QString servers1 = m_gridInfo->value(qsSection+LIST_CFG_USER_ID).toString();
    QStringList lvUserIndexs = strutils::explode(SEPARATOR_RECORD[0], servers1);
    QList<QString> list;
    for (int i = 0; i < lvUserIndexs.size(); ++i)
    {
        list.insert(list.begin() + i, lvUserIndexs.at(i));
    }

    return list;
}

void CColumnConfig::GetRoleNames(const QString qsSection, QHash<int, QByteArray>& roleNames,QStringList& dIndex)
{
    QString servers1 = m_gridInfo->value(qsSection+LIST_CFG_USER_ID).toString();
    QStringList lvUserIndexs = strutils::explode(SEPARATOR_RECORD[0], servers1);
    int role = Qt::UserRole;
    for (int i = 0; i < lvUserIndexs.size(); ++i)
    {
        roleNames.insert(role+i, lvUserIndexs.at(i).toLatin1());
    }

    QString servers2 = m_gridInfo->value(qsSection+LIST_CFG_INDEX).toString();
    dIndex = strutils::explode(SEPARATOR_RECORD[0], servers2);
}

QList<int> CColumnConfig::getColumnWidths(QString qsSection)
{
    QString servers1 = m_gridInfo->value(qsSection+LIST_CFG_WIDTH).toString();
//    QStringList lAligns = servers1.split(SEPARATOR_RECORD[0]);
    QStringList lAligns = strutils::explode(SEPARATOR_RECORD[0], servers1);
    QList<int> list;
    for (size_t i = 0; i < lAligns.size(); ++i)
    {
        list.append(lAligns.at(i).toInt());
    }

    return list;
}

QList<int> CColumnConfig::getColumnAligns( QString qsSection )
{
    QString servers1 = m_gridInfo->value(qsSection+LIST_CFG_ALIGN).toString();
    QStringList lAligns = strutils::explode(SEPARATOR_RECORD[0], servers1);

	QList<int> list;
    for (int i = 0; i < lAligns.size(); ++i)
	{
        list.append(lAligns.at(i).toInt());
	}

	return list;
}

QList<QString> CColumnConfig::getTitles(QString qsSection)
{
    QString servers = m_gridInfo->value(qsSection+LIST_CFG_ID).toString();
    QStringList lNames = strutils::explode(SEPARATOR_RECORD[0], servers);
    QString servers2 = m_gridInfo->value(qsSection+LIST_CFG_NAME).toString();
    QStringList lCNNames = strutils::explode(SEPARATOR_RECORD[0], servers2);

    QString servers1 = m_gridInfo->value(qsSection+LIST_CFG_USER_ID).toString();
    QStringList lvUserIndexs = strutils::explode(SEPARATOR_RECORD[0], servers1);
    qDebug()<<"getTitles:"<<servers<<" size"<<lvUserIndexs.size();
    QList<QString> list;
    for (int i = 0; i < lvUserIndexs.size(); ++i)
    {
        int nIndex = lNames.indexOf(lvUserIndexs.at(i));
        if ( nIndex >= lCNNames.size() || nIndex < 0)
        {
            qDebug()<<qsSection<<" getTitles列配置错误， "<<lvUserIndexs.at(i);
            break;
        }

        //list.append(vIDs[nIndex].c_str());
        list.insert(list.begin() + i, lCNNames.at(nIndex));
    }

    return list;
}

ColumnListModel* CColumnConfig::getColumnModel(QString qsSection)
{
    ColumnListModel* pModel = new ColumnListModel;
    QString servers = m_gridInfo->value(qsSection+LIST_CFG_ID).toString();
    QStringList lNames = strutils::explode(SEPARATOR_RECORD[0], servers);
    QString servers2 = m_gridInfo->value(qsSection+LIST_CFG_NAME).toString();
    QStringList lCNNames = strutils::explode(SEPARATOR_RECORD[0], servers2);

    QString servers1 = m_gridInfo->value(qsSection+LIST_CFG_USER_ID).toString();
    QStringList lvUserIndexs = strutils::explode(SEPARATOR_RECORD[0], servers1);
    QString servers3 = m_gridInfo->value(qsSection+LIST_CFG_ALIGN).toString();
    QStringList lAligns = strutils::explode(SEPARATOR_RECORD[0], servers3);
    qDebug()<<"lNames.size:"<<lNames.size()<<" lCNNames.size"<<lCNNames.size()<<" lvUserIndexs.size:"<<lvUserIndexs.size();
    int nSeq = 1;
    for (int i = 0; i < lvUserIndexs.size(); ++i)
    {
        int nIndex = lNames.indexOf(lvUserIndexs.at(i));
        if ( nIndex >= lAligns.size() ||nIndex >= lCNNames.size() || nIndex < 0)
            continue;
        ColumnItem item;
        item.name = lCNNames.at(nIndex);
        item.align = lAligns.at(nIndex).toInt();
        item.ID = lvUserIndexs.at(i);
        item.show = 1;
        item.index = nSeq++;

        pModel->addData(item);
    }

    for (int i = 0; i < lNames.size(); ++i)
    {
        int nIndex = lvUserIndexs.indexOf(lNames.at(i));
        if (nIndex < 0)
        {
            ColumnItem item;
            item.name = lCNNames.at(i);
            item.align = lAligns.at(i).toInt();
            item.ID = lNames.at(i);
            item.show = 0;
            item.index = nSeq++;

            pModel->addData(item);
        }
    }
	return pModel;
}

//保存显示列及顺序
void CColumnConfig::saveColumnCfg( QString qsSection, ColumnListModel* pModel )
{
    int nDel = 0; //清空name或者ID则删除，
    QList<ColumnItem> list = pModel->GetData();
    QString sUserIndex;
    QMap<int, ColumnItem> mapNames;
    for (int k = 0; k < list.size(); ++k)
    {
        if (list[k].ID.isEmpty() || list[k].name.isEmpty())
        {
            nDel++;
            continue;
        }

        mapNames[list[k].index] = list[k];
        if (list[k].show == 1)
        {
            //string sShowName = list[k].name.toLocal8Bit().data();
            sUserIndex += list[k].ID;
            sUserIndex += SEPARATOR_RECORD[0];
        }
    }

    QString sIDs,sName,sAlign,sFmt;
    qDebug()<<"保存列数："<<mapNames.size();
    auto it = mapNames.begin();
    while (it != mapNames.end())
    {
//        if (it.value().ID.isEmpty() || it.value().name.isEmpty())
//        {
//            it++;
//            continue;
//        }

        sIDs += it.value().ID;
        sIDs += SEPARATOR_RECORD[0];

        sName += it.value().name;
        sName += SEPARATOR_RECORD[0];

        sAlign += QString::number(it.value().align);
        sAlign += SEPARATOR_RECORD[0];

        it++;
    }

    qDebug()<<qsSection<<" cols sName:"<<sName;
    qDebug()<<qsSection<<" ini code des:"<<m_gridInfo->iniCodec()->name();
    m_gridInfo->setValue(qsSection+LIST_CFG_USER_ID,sUserIndex);
    m_gridInfo->setValue(qsSection+LIST_CFG_ID,sIDs);
    m_gridInfo->setValue(qsSection+LIST_CFG_NAME,sName);
    m_gridInfo->setValue(qsSection+LIST_CFG_ALIGN,sAlign);
    qDebug()<<qsSection<<" ini code des2:"<<m_gridInfo->iniCodec()->name();
    m_gridInfo->sync();//注意：修改原有设置不能立即生效，可使用sync()提交更改
}

void CColumnConfig::setColumnWidth(QString qsSection, QString qsRole, int nWidth)
{
    m_mapWidth[qsSection][qsRole] = nWidth;
}

void CColumnConfig::saveColumnWidth()
{
    auto itSection = m_mapWidth.begin();
    while (itSection != m_mapWidth.end())
    {
        QString servers = m_gridInfo->value(itSection.key()+LIST_CFG_ID).toString();
        QStringList lNames = strutils::explode(SEPARATOR_RECORD[0], servers);
        QString servers2 = m_gridInfo->value(itSection.key()+LIST_CFG_WIDTH).toString();
        QStringList lWidths = strutils::explode(SEPARATOR_RECORD[0], servers2);

        auto itRole = itSection.value().begin();
        while (itRole != itSection.value().end())
        {
            int nPos = lNames.indexOf(itRole.key());
            if (nPos >=0 && nPos < lWidths.size())
                lWidths.replace(nPos, QString::number(itRole.value()));

            itRole++;
        }

        QString sWidth;
        QMap<int, ColumnItem> mapNames;
        for (int k = 0; k < lWidths.size(); ++k)
        {
             sWidth += lWidths.at(k);
             sWidth += SEPARATOR_RECORD[0];
        }

        m_gridInfo->setValue(itSection.key()+LIST_CFG_WIDTH,sWidth);
        itSection++;
    }

    m_mapWidth.clear();
}

int ColumnListModel::rowCount(const QModelIndex &parent) const
{
	return m_vData.size();   
}

QVariant ColumnListModel::data(const QModelIndex &index, int role) const
{
	if (m_vData.size() == 0)
		return NULL;

	if (0 == role - Qt::UserRole)
		return m_vData[index.row()].name;
	else if (1 == role - Qt::UserRole)
	{
		return m_vData[index.row()].ID;
	}
	else if (2 == role - Qt::UserRole)
	{
		return m_vData[index.row()].align;
	}
	else if (3 == role - Qt::UserRole)
	{
		return m_vData[index.row()].show;
	}
	else if (4 == role - Qt::UserRole)
	{
		return m_vData[index.row()].index;
	}
	else if (5 == role - Qt::UserRole)
	{
//        CRLog(E_DEBUG, "this %d", (unsigned int)this);
//        if (!m_vData[index.row()].fmt.isEmpty())
//        {
//            CRLog(E_DEBUG, "Fmt %d=%s",index.row(),m_vData[index.row()].fmt.toLocal8Bit().data());
//        }
		return m_vData[index.row()].fmt;
	}
	else if (6 == role - Qt::UserRole)
	{	
		return m_vData[index.row()].fmtExtra;
	}
	return "";
}

QHash<int, QByteArray> ColumnListModel::roleNames() const
{
	return m_roleNames;
}

ColumnListModel::ColumnListModel()
{
	int role = Qt::UserRole;
	m_roleNames.insert(role++, "name");
	m_roleNames.insert(role++, "enName");
	m_roleNames.insert(role++, "align");
	m_roleNames.insert(role++, "show");
	m_roleNames.insert(role++, "defIndex");
	m_roleNames.insert(role++, "fmt");
	m_roleNames.insert(role++, "fmtExtra");
}

//void ColumnListModel::InitData( QList<Pair*> list )
//{
//	ClearTemp();
//	beginResetModel();
//	m_vData  = list;
//	endResetModel();
//}

int ColumnListModel::addData(ColumnItem it)
{
	for (int i = 0; i < m_vData.size();++i)
	{
		if (m_vData[i].index == it.index)
		{
			return -1;
		}
	}

	m_vData.append(it);

	return 0;
}

void ColumnListModel::moveUp(int nFocus)
{
	beginMoveRows(QModelIndex(),nFocus, nFocus,QModelIndex(), nFocus-1);
	ColumnItem pTemp = m_vData[nFocus-1];
	m_vData[nFocus-1] = m_vData[nFocus];
	m_vData[nFocus] = pTemp;
	endMoveRows();
}

void ColumnListModel::moveDown(int nFocus)
{
	beginMoveRows(QModelIndex(),nFocus+1, nFocus+1,QModelIndex(), nFocus);
	//beginMoveRows(QModelIndex(),nFocus, nFocus,QModelIndex(), nFocus+1);
	ColumnItem pTemp = m_vData[nFocus+1];
	m_vData[nFocus+1] = m_vData[nFocus];
	m_vData[nFocus] = pTemp;
	endMoveRows();
}

void ColumnListModel::setCheck(int nFocus, bool bCheck)
{
	bCheck ? m_vData[nFocus].show = 1 : m_vData[nFocus].show = 0;
}

//void ColumnListModel::ClearTemp()
//{
//	for (int i = 0; i < m_vTempData.size();++i)
//	{
//		delete m_vTempData[i];
//	}
//
//	m_vTempData.clear();
//}



ColumnListModel::~ColumnListModel()
{

}

QList<ColumnItem> ColumnListModel::GetData()
{
	return m_vData;
}

void ColumnListModel::setName( int nFocus, QString name )
{
	if (nFocus < 0 || nFocus >= m_vData.size())
	{
		return;
	} 
	
	m_vData[nFocus].name = name;
}

void ColumnListModel::setEnName( int nFocus, QString name )
{
	if (nFocus < 0 || nFocus >= m_vData.size())
	{
		return;
	} 
	m_vData[nFocus].ID = name;
}

void ColumnListModel::setAlign( int nFocus, int nAlign )
{
	if (nFocus < 0 || nFocus >= m_vData.size())
	{
		return;
	} 
	m_vData[nFocus].align = nAlign;
}

void ColumnListModel::setFmt( int nFocus, QString name )
{
	if (nFocus < 0 || nFocus >= m_vData.size())
	{
		return;
	} 
	m_vData[nFocus].fmt = name;
//	CRLog(E_DEBUG, "setFmt=%s", name.toLocal8Bit().data());
}

void ColumnListModel::setFmtExtra( int nFocus, QString name )
{
	if (nFocus < 0 || nFocus >= m_vData.size())
	{
		return;
	} 
	m_vData[nFocus].fmtExtra = name;
}

void ColumnListModel::insertRow()
{
	beginResetModel();
	//beginInsertRows(QModelIndex(),m_vData.size()-1,m_vData.size()-1);
	ColumnItem it;
	it.index = m_vData.size();
	it.align = 0;
	m_vData.push_back(it);
	//endInsertRows();
	endResetModel();
}

